package iotwisp.school.wx.service;

import com.alibaba.fastjson.JSON;
import iotwisp.base.cqrs.BusinessException;
import iotwisp.base.orm.BaseDao;
import iotwisp.base.util.HttpResponse;
import iotwisp.base.util.HttpUtil;
import iotwisp.school.config.IotWispSchoolConfig;
import iotwisp.school.wx.command.GetAccessTokenSCmd;
import iotwisp.school.wx.command.RefreshAccessTokenSCmd;
import iotwisp.school.wx.dto.WxGetAccessTokenResponse;
import iotwisp.school.wx.entity.WxUser;
import iotwisp.school.wx.qo.WxUserQO;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class WxUserService extends BaseDao<WxUser, WxUserQO> {

    @Autowired
    private IotWispSchoolConfig config;

    public WxUser getAccessToken(GetAccessTokenSCmd cmd) throws BusinessException {

        HttpResponse httpResponse = HttpUtil.reqForGet(
                config.getWx().getGetAccessTokenApiUrl() +
                        "?appid=" + config.getWx().getAppId() + "&secret=" + config.getWx().getAppSecret() + "&code=" + cmd.getCode() + "&grant_type=authorization_code",
                30000);
        WxGetAccessTokenResponse response = JSON.parseObject(httpResponse.getResult(), WxGetAccessTokenResponse.class);

        if (response.getErrcode() != 0) {
            throw BusinessException.getInstance(BusinessException.STATUS_NOT_ALLOW, response.getErrmsg());
        }
        WxUser wxUser = null;
        if (StringUtils.isNotBlank(cmd.getHeader().getCurrentUserId())) {
            WxUserQO qo = new WxUserQO();
            qo.setUserId(cmd.getHeader().getCurrentUserId());
            qo.setFetchUser(true);
            wxUser = queryUnique(qo);
            wxUser.refresh(response);
        } else {
            wxUser.create(response);
        }

        return wxUser;
    }

    public WxUser refreshAccessToken(RefreshAccessTokenSCmd cmd) throws BusinessException {

        WxUser wxUser = get(cmd.getWxUserId());

        HttpResponse httpResponse = HttpUtil.reqForGet(
                config.getWx().getGetAccessTokenApiUrl() +
                        "?appid=" + config.getWx().getAppId() + "&grant_type=refresh_token&refresh_token=" + wxUser.getRefreshToken(),
                30000);
        WxGetAccessTokenResponse response = JSON.parseObject(httpResponse.getResult(), WxGetAccessTokenResponse.class);
        if (response.getErrcode() != 0) {
            throw BusinessException.getInstance(BusinessException.STATUS_NOT_ALLOW, response.getErrmsg());
        }

        wxUser.refresh(response);
        update(wxUser);

        return wxUser;
    }

    @Override
    protected Criteria buildCriteria(Criteria criteria, WxUserQO qo) {
        return criteria;
    }

    @Override
    protected Class<WxUser> getEntityClass() {
        return WxUser.class;
    }

}
